<template>
  <el-dialog
    title="添加待办事项"
    v-model="dialogVisible"
    :width="dialogWidth"
    top="5vh"
    :fullscreen="isMobile"
    :append-to-body="true"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="todoForm"
      :rules="rules"
      label-position="top"
      class="responsive-form"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="todoForm.title" placeholder="请输入待办事项标题" />
      </el-form-item>
      
      <el-form-item label="描述" prop="description">
        <el-input
          v-model="todoForm.description"
          type="textarea"
          rows="3"
          placeholder="请输入待办事项描述"
        />
      </el-form-item>
      
      <el-form-item label="分类" prop="categoryId">
        <el-select
          v-model="todoForm.categoryId"
          placeholder="选择分类"
          style="width: 100%"
        >
          <el-option
            v-for="category in todoStore.categories"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
        
        <div class="add-new-link">
          <a href="#" @click.prevent="showAddCategory = true">添加新分类</a>
        </div>
      </el-form-item>
      
      <el-form-item label="标签" prop="tags">
        <el-select
          v-model="todoForm.tags"
          multiple
          placeholder="选择标签"
          style="width: 100%"
        >
          <el-option
            v-for="tag in todoStore.tags"
            :key="tag.id"
            :label="tag.name"
            :value="tag.id"
          />
        </el-select>
        
        <div class="add-new-link">
          <a href="#" @click.prevent="showAddTag = true">添加新标签</a>
        </div>
      </el-form-item>
      
      <el-form-item label="截止日期" prop="dueDate">
        <el-date-picker
          v-model="todoForm.dueDate"
          type="date"
          placeholder="选择截止日期"
          style="width: 100%"
        />
      </el-form-item>
      
      <el-form-item label="优先级" prop="priority">
        <el-radio-group v-model="todoForm.priority">
          <el-radio :label="1">低</el-radio>
          <el-radio :label="2">中</el-radio>
          <el-radio :label="3">高</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="isSubmitting">
          添加
        </el-button>
      </span>
    </template>
    
    <!-- 添加分类对话框 -->
    <el-dialog
      v-model="showAddCategory"
      title="添加新分类"
      :width="dialogWidth"
      :fullscreen="isMobile"
      append-to-body
    >
      <el-form :model="newCategory" label-position="top" class="responsive-form">
        <el-form-item label="分类名称" required>
          <el-input v-model="newCategory.name" placeholder="请输入分类名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddCategory = false">取消</el-button>
          <el-button type="primary" @click="addNewCategory" :loading="isAddingCategory">
            添加
          </el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 添加标签对话框 -->
    <el-dialog
      v-model="showAddTag"
      title="添加新标签"
      :width="dialogWidth"
      :fullscreen="isMobile"
      append-to-body
    >
      <el-form :model="newTag" label-position="top" class="responsive-form">
        <el-form-item label="标签名称" required>
          <el-input v-model="newTag.name" placeholder="请输入标签名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddTag = false">取消</el-button>
          <el-button type="primary" @click="addNewTag" :loading="isAddingTag">
            添加
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, computed, onMounted, onBeforeUnmount } from 'vue'
import { useTodoStore } from '../../stores/todo'
import { ElMessage } from 'element-plus'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'add'])

const todoStore = useTodoStore()
const formRef = ref(null)
const isSubmitting = ref(false)
const showAddCategory = ref(false)
const showAddTag = ref(false)
const isAddingCategory = ref(false)
const isAddingTag = ref(false)
const windowWidth = ref(window.innerWidth)

const dialogVisible = ref(props.visible)

// 监听窗口大小变化
const handleResize = () => {
  windowWidth.value = window.innerWidth
}

// 计算对话框宽度
const dialogWidth = computed(() => {
  if (windowWidth.value < 768) {
    return '95%'
  } else if (windowWidth.value < 992) {
    return '80%'
  } else {
    return '500px'
  }
})

// 判断是否为移动设备
const isMobile = computed(() => {
  return windowWidth.value < 768
})

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})

watch(() => props.visible, (val) => {
  dialogVisible.value = val
})

watch(() => dialogVisible.value, (val) => {
  emit('update:visible', val)
})

const todoForm = reactive({
  title: '',
  description: '',
  categoryId: null,
  tags: [],
  dueDate: null,
  priority: 2,
  completed: false
})

const newCategory = reactive({
  name: ''
})

const newTag = reactive({
  name: ''
})

const rules = {
  title: [
    { required: true, message: '请输入待办事项标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ]
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  todoForm.title = ''
  todoForm.description = ''
  todoForm.categoryId = null
  todoForm.tags = []
  todoForm.dueDate = null
  todoForm.priority = 2
  todoForm.completed = false
}

const handleClose = () => {
  resetForm()
}

const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      isSubmitting.value = true
      try {
        // 处理日期格式
        const formData = { ...todoForm }
        if (formData.dueDate) {
          formData.dueDate = formData.dueDate.toISOString()
        }
        
        // 将tags字段改为tagIds字段，并移除priority字段
        if (formData.tags) {
          formData.tagIds = formData.tags
          delete formData.tags
        }
        
        // 移除priority字段，因为后端不支持
        delete formData.priority
        
        emit('add', formData)
        resetForm()
        dialogVisible.value = false
      } catch (error) {
        console.error('添加待办事项失败:', error)
        ElMessage.error('添加待办事项失败')
      } finally {
        isSubmitting.value = false
      }
    }
  })
}

const addNewCategory = async () => {
  if (!newCategory.name.trim()) {
    ElMessage.warning('请输入分类名称')
    return
  }
  
  isAddingCategory.value = true
  try {
    const category = await todoStore.addCategory(newCategory)
    if (category) {
      todoForm.categoryId = category.id
      ElMessage.success('分类添加成功')
      showAddCategory.value = false
      newCategory.name = ''
    }
  } catch (error) {
    console.error('添加分类失败:', error)
    ElMessage.error('添加分类失败')
  } finally {
    isAddingCategory.value = false
  }
}

const addNewTag = async () => {
  if (!newTag.name.trim()) {
    ElMessage.warning('请输入标签名称')
    return
  }
  
  isAddingTag.value = true
  try {
    const tag = await todoStore.addTag(newTag)
    if (tag) {
      todoForm.tags.push(tag.id)
      ElMessage.success('标签添加成功')
      showAddTag.value = false
      newTag.name = ''
    }
  } catch (error) {
    console.error('添加标签失败:', error)
    ElMessage.error('添加标签失败')
  } finally {
    isAddingTag.value = false
  }
}
</script>

<style scoped>
.responsive-form {
  max-width: 100%;
}

.add-new-link {
  margin-top: 8px;
  font-size: 14px;
}

@media (max-width: 768px) {
  :deep(.el-dialog__body) {
    padding: 15px;
  }
  
  :deep(.el-form-item) {
    margin-bottom: 15px;
  }
  
  :deep(.el-select) {
    width: 100% !important;
  }
  
  :deep(.el-date-picker) {
    width: 100% !important;
  }
  
  :deep(.el-dialog__footer) {
    padding: 10px 15px;
  }
  
  :deep(.dialog-footer) {
    display: flex;
    justify-content: space-between;
    width: 100%;
  }
  
  :deep(.dialog-footer .el-button) {
    flex: 1;
    margin-left: 8px;
  }
  
  :deep(.dialog-footer .el-button:first-child) {
    margin-left: 0;
  }
}
</style>